import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:nyh_motorcade_app/constant/constant.dart';
import 'package:nyh_motorcade_app/utils/toast_utils.dart';
import 'package:nyh_motorcade_app/widgets/loading_dialog.dart';
import 'package:permission_handler/permission_handler.dart';

class DriverCodeController extends GetxController {
  GlobalKey repaintGlobalKey = new GlobalKey();
  String companyId = "";
  String companyName = "";
  String motorcadeId = "";
  String motorcadeName = "";
  bool isOwnDriver = true;
  bool isCreatedCode = false;
  String qrCodeData = "";

  @override
  void onReady() {
    super.onReady();
    dynamic arguments = Get.arguments;
    if (arguments != null && arguments is Map) {
      companyId = arguments[Constant.PARAM_COMPANY_ID];
      companyName = arguments[Constant.PARAM_COMPANY_NAME];
      update();
    }
  }

  void changeDriverType(bool isOwn) {
    if (isOwnDriver != isOwn) {
      isOwnDriver = isOwn;
      update();
    }
  }

  void createQrCode(String data) {
    qrCodeData = data;
    isCreatedCode = true;
    update();
  }

  Future<void> saveQrCode() async {
    PermissionStatus status = await Permission.storage.request();
    if (status != PermissionStatus.granted) {
      ToastUtils.toast("请打开存储权限");
      return;
    }
    LoadingDialog.showCustomDialog(Get.context, message: "保存中...");
    try {
      RenderRepaintBoundary boundary = repaintGlobalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
      ui.Image image = await boundary.toImage(pixelRatio: MediaQuery.of(Get.context!).devicePixelRatio);
      ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      if (byteData != null) {
        Map result = await ImageGallerySaver.saveImage(byteData.buffer.asUint8List(), quality: 100, isReturnImagePathOfIOS: true);
        print("保存图片结果:$result");
        bool isSuccess = result["isSuccess"];
        if (isSuccess) {
          String filePath = result["filePath"];
          if (filePath.isNotEmpty && filePath.contains("file://")) {
            filePath = filePath.replaceAll("file://", "");
          }
          ToastUtils.toast("图片已保存至$filePath");
        } else {
          ToastUtils.toast("保存图片失败:${result["errorMessage"]}");
        }
      } else {
        ToastUtils.toast("保存图片失败");
      }
      LoadingDialog.dismissDialog(Get.context);
    } catch (e) {
      LoadingDialog.dismissDialog(Get.context);
      ToastUtils.toast("保存图片失败:${e.toString()}");
    }
  }
}
